﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;

namespace HZ.Supervise.Web.Secondphase.Comparison
{
    public partial class ComparisonByProSettlement : BasePage
    {
        DataTable dt = new DataTable();
        DataTable dt2 = new DataTable();
        Dictionary<string, string> dicProductName = new Dictionary<string, string>();
        string[] pid = { };
        string pids = "";
        string timefrom = "";
        string timeto = "";
        SeriesChartType t = SeriesChartType.Line;
        protected void Page_Load(object sender, EventArgs e)
        {
            txtProName.Attributes.Add("readonly", "readonly");
            txtHosName.Attributes.Add("readonly", "readonly");
            txtAeraName.Attributes.Add("readonly", "readonly");
            if (IsPostBack)
            {
                pids = HidProId.Value.Trim();
                pid = pids.Split(',');
                timefrom = txtStratTime.Text.Trim();
                timeto = txtEndTime.Text.Trim();
                this.HidProId.Value = pids;
                string a = this.txtProName.Text.Trim();
            }


        }

        private void dataBind()
        {
            StringBuilder strid = new StringBuilder();
            StringBuilder where2 = new StringBuilder();
            if (pid.Length < 1)
            {
                this.Page.RegisterStartupScript("", "<script>alert('请选择对比的药品')</script>");
                return;
            }
            if (timeto.Length < 1 && timefrom.Length < 1)
            {
                this.Page.RegisterStartupScript("", "<script>alert('请选择对比时间')</script>");
                return;
            }
            foreach (string item in pid)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    strid.Append("'" + item + "',");
                }
            }
            if (!string.IsNullOrEmpty(timefrom))
            {
                where2.Append(" and PSubmitTime> '" + timefrom + "'");
            }
            if (!string.IsNullOrEmpty(timeto))
            {
                where2.Append(" and PSubmitTime< '" + timeto + "'");
            }
            if (!string.IsNullOrEmpty(hidArea.Value))
            {
                where2.Append(" and PAreaId = '" + hidArea.Value + "'");
            }
            if (!string.IsNullOrEmpty(hidHos.Value))
            {
                where2.Append(" and PHospitalId = '" + hidHos.Value + "'");
            }
            string sql = "select GoodsID,ProductName from TB_Goods where GoodsID in(" + strid.Remove(strid.Length - 1, 1).ToString() + ") ";
            string sql1 = "select ProcureCatalogID,SUM(Pamount) as Pamount,SUM(Pcount) as Pcount,SUM(PSubsidiesAmount) as PSubsidiesAmount,dbo.fun_GetYearMonth(PSubmitTime)  as Time from View_Prescription where  POrderStatus>0 and  ProcureCatalogID in (" + strid.ToString() + ") " + where2 + " group by dbo.fun_GetYearMonth(PSubmitTime),ProcureCatalogID";
            HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();

            string sql2 = "select dbo.fun_GetYearMonth(PSubmitTime) as Time,sum(Pamount) as Pamount ,sum(Pcount) as Pcount from View_Prescription where  POrderStatus>0 group by dbo.fun_GetYearMonth(PSubmitTime)";
            DataTable dtProductName = iPrescription.GetSubsidyStatistics(sql);
            dt = iPrescription.GetSubsidyStatistics(sql1);
            dt2 = iPrescription.GetSubsidyStatistics(sql2);
            for (int i = 0; i < dtProductName.Rows.Count; i++)
            {
                dicProductName.Add(dtProductName.Rows[i]["GoodsID"].ToString(), dtProductName.Rows[i]["ProductName"].ToString());
            }
        }

        /// <summary>
        /// 得到时间段内一共有多少个月返回月份
        /// </summary>
        /// <param name="timefrom"></param>
        /// <param name="timeto"></param>
        /// <returns></returns>
        private List<string> GetPageMonthall(DateTime timefrom, DateTime timeto)
        {
            string year = timeto.Year.ToString(); //截至年份
            int nmonth = timeto.Month;//截至月份
            TimeSpan objT = timeto.Subtract(timefrom);//获得时间内一共多少时间
            int month2 = 0;
            if (timeto.Day == 1)//如果截至时间的一号的话
            {
                //如果是月头
                if (timefrom.Day == 1)
                {
                    month2 = System.Convert.ToInt32(objT.Days / ((365 / 12)));
                }
                else
                {
                    month2 = System.Convert.ToInt32(objT.Days / ((365 / 12))) + 1;
                }

            }
            else
            {
                if (objT.Days % ((365 / 12)) > timeto.Day)
                {
                    month2 = System.Convert.ToInt32(objT.Days / ((365 / 12))) + 2;
                }
                else
                {
                    month2 = System.Convert.ToInt32(objT.Days / ((365 / 12))) + 1;
                }

            }
            int nmm = 0;
            List<string> dd = new List<string>();
            for (int mm = nmonth; (mm > 0 && nmm < month2); mm--)
            {
                if (timeto.Day == 1)
                {
                    dd.Add(year + AddZeromonth(mm - 1));
                    if (mm - 1 == 1)
                    {
                        nmm++;
                        break;
                    }
                }
                else
                {
                    dd.Add(year + AddZeromonth(mm));
                }

                nmm++;
            }
            month2 = month2 - nmm;
            nmm = 0;
            int yuarTemp = 1;
            while (nmm < month2)
            {
                if (nmm < 12)
                {
                    dd.Add((Convert.ToInt32(year) - yuarTemp).ToString() + AddZeromonth(12 - nmm));
                    nmm++;
                }
                else
                {
                    month2 = month2 - 12;
                    nmm = 0;
                    yuarTemp++;
                    dd.Add((Convert.ToInt32(year) - yuarTemp).ToString() + AddZeromonth(12 - nmm));
                    nmm++;
                }
            }
            dd.Sort();
            return dd;
        }
        /// <summary>
        /// 给月份补0
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        public string AddZeromonth(int month)
        {
            if (month.ToString().Length < 2)
                return "0" + month.ToString();
            else
                return month.ToString();
        }


        private void chartBind()
        {
            if (dt.Rows.Count > 0)
            {
                //所有的图都能用
                this.Page.RegisterStartupScript("", "<script>dis('chart3');</script>");
                hospitalAmountSubsidy.Enabled = true;
                hospitalAmountSubsidy0.Enabled = true;
                hospitalAmountSubsidy2.Enabled = true;
                hospitalAmountSubsidy3.Enabled = true;
                this.lblnull.Enabled = false;

                Dictionary<string, Dictionary<string, double>> dicPamount = new Dictionary<string, Dictionary<string, double>>();//药品使用金额
                Dictionary<string, Dictionary<string, int>> dicPcount = new Dictionary<string, Dictionary<string, int>>();//药品使用数量
                Dictionary<string, double> dicSumPamount = new Dictionary<string, double>();//药品使用总金额
                Dictionary<string, int> dicSumPcount = new Dictionary<string, int>();//药品使用总数量
                Dictionary<string, Dictionary<string, double>> dicPSbsidyAmount = new Dictionary<string, Dictionary<string, double>>();//药品补贴金额

                for (int i = 0; i < pid.Length; i++)
                {
                    if (!pid[i].Equals(""))
                    {
                        dicPamount.Add(pid[i], new Dictionary<string, double>());
                        dicPcount.Add(pid[i], new Dictionary<string, int>());
                        dicPSbsidyAmount.Add(pid[i], new Dictionary<string, double>());
                    }
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dicPamount[dt.Rows[i]["ProcureCatalogID"].ToString()].Add(dt.Rows[i]["Time"].ToString(), double.Parse(dt.Rows[i]["Pamount"].ToString()));
                    dicPcount[dt.Rows[i]["ProcureCatalogID"].ToString()].Add(dt.Rows[i]["Time"].ToString(), int.Parse(dt.Rows[i]["Pcount"].ToString()));
                    dicPSbsidyAmount[dt.Rows[i]["ProcureCatalogID"].ToString()].Add(dt.Rows[i]["Time"].ToString(), double.Parse(dt.Rows[i]["PSubsidiesAmount"].ToString()));
                }
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    dicSumPamount.Add(dt2.Rows[i]["Time"].ToString(), double.Parse(dt2.Rows[i]["Pamount"].ToString()));
                    dicSumPcount.Add(dt2.Rows[i]["Time"].ToString(), int.Parse(dt2.Rows[i]["Pcount"].ToString()));
                }
                List<string> listmonth = GetPageMonthall(DateTime.Parse(timefrom), DateTime.Parse(timeto));
                //给没有值的月补值
                for (int i = 0; i < pid.Length - 1; i++)
                {
                    foreach (var item in listmonth)
                    {
                        if (!dicPamount[pid[i]].ContainsKey(item))
                        {
                            dicPamount[pid[i]].Add(item, 0);
                        } if (!dicPcount[pid[i]].ContainsKey(item))
                        {
                            dicPcount[pid[i]].Add(item, 0);
                        }
                        if (!dicPSbsidyAmount[pid[i]].ContainsKey(item))
                        {
                            dicPSbsidyAmount[pid[i]].Add(item, 0);
                        }
                        if (!dicSumPamount.ContainsKey(item))
                        {
                            dicSumPamount.Add(item, 0);
                        }
                        if (!dicSumPcount.ContainsKey(item))
                        {
                            dicSumPcount.Add(item, 0);
                        }
                    }
                }
                for (int i = 0; i < pid.Length - 1; i++)
                {
                    Series sess = new Series();
                    sess.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true);
                    sess.LegendText = dicProductName[pid[i]].ToString();
                    sess.IsValueShownAsLabel = true;
                    sess["DrawingStyle"] = "Emboss";
                    Series sess1 = new Series();
                    sess1.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true);
                    sess1.LegendText = dicProductName[pid[i]].ToString();
                    sess1.IsValueShownAsLabel = true;
                    sess1["DrawingStyle"] = "Emboss";
                    Series sess2 = new Series();
                    sess2.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true);
                    sess2.LegendText = dicProductName[pid[i]].ToString();
                    sess2.IsValueShownAsLabel = true;
                    sess2["DrawingStyle"] = "Emboss";
                    Series sess3 = new Series();
                    sess3.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true);
                    sess3.LegendText = dicProductName[pid[i]].ToString();
                    sess3.IsValueShownAsLabel = true;
                    sess3["DrawingStyle"] = "Emboss";
                    Series sess4 = new Series();
                    sess4.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true);
                    sess4.LegendText = dicProductName[pid[i]].ToString();
                    sess4.IsValueShownAsLabel = true;
                    sess4["DrawingStyle"] = "Emboss";
                    for (int j = 0; j < listmonth.Count; j++)
                    {
                        sess.Points.AddXY(listmonth[j].Substring(4) + "月", (dicPamount[pid[i]][listmonth[j]] / 10000).ToString("0.0000"));
                        sess2.Points.AddXY(listmonth[j].Substring(4) + "月", (dicPcount[pid[i]][listmonth[j]] / 10000).ToString("0.0000"));
                        sess1.Points.AddXY(listmonth[j].Substring(4) + "月", (dicPSbsidyAmount[pid[i]][listmonth[j]] / 10000).ToString("0.0000"));
                        sess.Points[j].ToolTip = (dicPamount[pid[i]][listmonth[j]] / 10000).ToString("0.0000");
                        sess2.Points[j].ToolTip = (dicPcount[pid[i]][listmonth[j]] / 10000).ToString("0.0000");
                        sess1.Points[j].ToolTip = (dicPSbsidyAmount[pid[i]][listmonth[j]] / 10000).ToString("0.0000");
                        if (dicSumPamount[listmonth[j]] != 0)
                        {
                            sess3.Points.AddXY(listmonth[j].Substring(4) + "月", ((dicPamount[pid[i]][listmonth[j]] / dicSumPamount[listmonth[j]]) * 100).ToString("0.00"));
                            sess4.Points.AddXY(listmonth[j].Substring(4) + "月", ((double.Parse(dicPcount[pid[i]][listmonth[j]].ToString()) / double.Parse(dicSumPcount[listmonth[j]].ToString())) * 100).ToString("0.00"));
                            sess3.Points[j].ToolTip  = ((dicPamount[pid[i]][listmonth[j]] / dicSumPamount[listmonth[j]]) * 100).ToString("0.00");
                            sess4.Points[j].ToolTip = ((double.Parse(dicPcount[pid[i]][listmonth[j]].ToString()) / double.Parse(dicSumPcount[listmonth[j]].ToString())) * 100).ToString("0.00");
                        }
                        else
                        {
                            sess3.Points.AddXY(listmonth[j].Substring(4) + "月", 0);
                            sess4.Points.AddXY(listmonth[j].Substring(4) + "月", 0);
                            sess3.Points[j].ToolTip  = "0";
                            sess4.Points[j].ToolTip = "0";
                        }

                    }
                    hospitalAmountSubsidy.Series.Add(sess);
                    hospitalAmountSubsidy1.Series.Add(sess1);
                    hospitalAmountSubsidy0.Series.Add(sess2);
                    hospitalAmountSubsidy2.Series.Add(sess3);
                    hospitalAmountSubsidy3.Series.Add(sess4);
                }

                hospitalAmountSubsidy.Titles.Add("使用总金额对比图");
                hospitalAmountSubsidy.Titles[0].Font = new Font("宋体", 16, FontStyle.Bold);
                hospitalAmountSubsidy.Titles[0].Position.X = 30;
                hospitalAmountSubsidy.Titles[0].Position.Y = 1;
                hospitalAmountSubsidy.Titles[0].Position.Width = 50;
                hospitalAmountSubsidy.Titles[0].Position.Height = 8;
                hospitalAmountSubsidy.ChartAreas["hospitalAmountSubsidy"].AxisY.Title = "金额(万元))";
                hospitalAmountSubsidy.ChartAreas["hospitalAmountSubsidy"].AxisX.Title = "月份";
                hospitalAmountSubsidy.ChartAreas["hospitalAmountSubsidy"].AxisX.Interval = 1;
                hospitalAmountSubsidy.ChartAreas["hospitalAmountSubsidy"].AxisX.IntervalOffset = 1;
                hospitalAmountSubsidy.ChartAreas["hospitalAmountSubsidy"].AxisX.LabelStyle.IsStaggered = true;


                hospitalAmountSubsidy0.Titles.Add("使用总数量对比图");
                hospitalAmountSubsidy0.Titles[0].Font = new Font("宋体", 16, FontStyle.Bold);
                hospitalAmountSubsidy0.Titles[0].Position.X = 30;
                hospitalAmountSubsidy0.Titles[0].Position.Y = 1;
                hospitalAmountSubsidy0.Titles[0].Position.Width = 50;
                hospitalAmountSubsidy0.Titles[0].Position.Height = 8;
                hospitalAmountSubsidy0.ChartAreas["hospitalAmountSubsidy0"].AxisY.Title = "金额(万元)";
                hospitalAmountSubsidy0.ChartAreas["hospitalAmountSubsidy0"].AxisX.Title = "月份";
                hospitalAmountSubsidy0.ChartAreas["hospitalAmountSubsidy0"].AxisX.Interval = 1;
                hospitalAmountSubsidy0.ChartAreas["hospitalAmountSubsidy0"].AxisX.IntervalOffset = 1;
                hospitalAmountSubsidy0.ChartAreas["hospitalAmountSubsidy0"].AxisX.LabelStyle.IsStaggered = true;


                hospitalAmountSubsidy1.Titles.Add("补贴总金额对比图");
                hospitalAmountSubsidy1.Titles[0].Font = new Font("宋体", 16, FontStyle.Bold);
                hospitalAmountSubsidy1.Titles[0].Position.X = 30;
                hospitalAmountSubsidy1.Titles[0].Position.Y = 1;
                hospitalAmountSubsidy1.Titles[0].Position.Width = 50;
                hospitalAmountSubsidy1.Titles[0].Position.Height = 8;
                hospitalAmountSubsidy1.ChartAreas["hospitalAmountSubsidy1"].AxisY.Title = "金额(万元)";
                hospitalAmountSubsidy1.ChartAreas["hospitalAmountSubsidy1"].AxisX.Title = "月份";
                hospitalAmountSubsidy1.ChartAreas["hospitalAmountSubsidy1"].AxisX.Interval = 1;
                hospitalAmountSubsidy1.ChartAreas["hospitalAmountSubsidy1"].AxisX.IntervalOffset = 1;
                hospitalAmountSubsidy1.ChartAreas["hospitalAmountSubsidy1"].AxisX.LabelStyle.IsStaggered = true;


                hospitalAmountSubsidy2.Titles.Add("使用率(金额)对比图");
                hospitalAmountSubsidy2.Titles[0].Font = new Font("宋体", 16, FontStyle.Bold);
                hospitalAmountSubsidy2.Titles[0].Position.X = 30;
                hospitalAmountSubsidy2.Titles[0].Position.Y = 1;
                hospitalAmountSubsidy2.Titles[0].Position.Width = 50;
                hospitalAmountSubsidy2.Titles[0].Position.Height = 8;
                hospitalAmountSubsidy2.ChartAreas["hospitalAmountSubsidy2"].AxisY.Title = "比例(%)";
                hospitalAmountSubsidy2.ChartAreas["hospitalAmountSubsidy2"].AxisX.Title = "月份";
                hospitalAmountSubsidy2.ChartAreas["hospitalAmountSubsidy2"].AxisX.Interval = 1;
                hospitalAmountSubsidy2.ChartAreas["hospitalAmountSubsidy2"].AxisX.IntervalOffset = 1;
                hospitalAmountSubsidy2.ChartAreas["hospitalAmountSubsidy2"].AxisX.LabelStyle.IsStaggered = true;


                hospitalAmountSubsidy3.Titles.Add("使用率(数量)对比图");
                hospitalAmountSubsidy3.Titles[0].Font = new Font("宋体", 16, FontStyle.Bold);
                hospitalAmountSubsidy3.Titles[0].Position.X = 30;
                hospitalAmountSubsidy3.Titles[0].Position.Y = 1;
                hospitalAmountSubsidy3.Titles[0].Position.Width = 50;
                hospitalAmountSubsidy3.Titles[0].Position.Height = 8;
                hospitalAmountSubsidy3.ChartAreas["hospitalAmountSubsidy3"].AxisY.Title = "比例(%)";
                hospitalAmountSubsidy3.ChartAreas["hospitalAmountSubsidy3"].AxisX.Title = "月份";
                hospitalAmountSubsidy3.ChartAreas["hospitalAmountSubsidy3"].AxisX.Interval = 1;
                hospitalAmountSubsidy3.ChartAreas["hospitalAmountSubsidy3"].AxisX.IntervalOffset = 1;
                hospitalAmountSubsidy3.ChartAreas["hospitalAmountSubsidy3"].AxisX.LabelStyle.IsStaggered = true;


            }
            else
            {
                hospitalAmountSubsidy.Enabled = false;
                hospitalAmountSubsidy0.Enabled = false;
                hospitalAmountSubsidy1.Enabled = false;
                hospitalAmountSubsidy2.Enabled = false;
                hospitalAmountSubsidy3.Enabled = false;
                this.lblnull.Enabled = true;
            }

        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            dataBind();
            chartBind();
        }


    }
}
